/*
 * JDialogPreferencias.java
 *
 * Created on 30-sep-2011, 10:16:06
 */
package com.ufps.cuatro.vistas.representacion;

import java.util.Observable;
import java.util.Observer;

import javax.swing.table.TableColumn;

import org.jdesktop.application.Action;

import com.ufps.cuatro.CuatroApp;
import com.ufps.cuatro.util.Bandera;
import com.ufps.cuatro.util.Utileria;
import com.ufps.cuatro.util.editor.ColumnCellEditorPreferencesColumnValues;
import com.ufps.cuatro.util.model.MyTableModelPreferences;
import com.ufps.cuatro.util.opciones.TypeOptionPreferences;
import com.ufps.cuatro.util.opciones.UtilOpciones;
import com.ufps.cuatro.util.render.ColumnCellRendererPreferencesColumnValues;
import com.ufps.cuatro.controlador.render.UtilRender;

/**
 *
 * @author Carlos A. Torres C. 
 */
public class JDialogPreferencias extends javax.swing.JDialog implements Observer{
    private static final long serialVersionUID = -1693970063385075109L;
    
    private Object objParent;

    /** Creates new form JDialogPreferencias */
    public JDialogPreferencias(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents(); 
        this.setIconImage(Utileria.leerIconoAppEnImagen(Utileria.MODO_16x16).getImage());
    }

    public JDialogPreferencias(Object objParent) {
        super(CuatroApp.getApplication().getMainFrame(), true);
        initComponents();
        this.setIconImage(Utileria.leerIconoAppEnImagen(Utileria.MODO_16x16).getImage());
        this.objParent = objParent;
        
        this.jTablePreferences.setModel(UtilOpciones.crearTablaOpciones(objParent));
        TableColumn objColumnaValor = this.jTablePreferences.getColumn(MyTableModelPreferences.NAME_COLUMN_VALUES);
        objColumnaValor.setCellRenderer(new ColumnCellRendererPreferencesColumnValues());    
        objColumnaValor.setCellEditor(new ColumnCellEditorPreferencesColumnValues());
        this.jTablePreferences.setRowHeight(24);
        this.ajustarAnchoColumnas();
    }
    
    private void ajustarAnchoColumnas(){
        int max = maxSpaceCols();
        for(int i = 0; i < jTablePreferences.getColumnCount(); i++) {
            jTablePreferences.getColumnModel().getColumn(i).setPreferredWidth(max);
        }
    }
    
    private int maxSpaceCols(){
        int max = 20;         
        for(int i = 0; i <  this.jTablePreferences.getRowCount(); i++){
            if(jTablePreferences.getValueAt(i, 0) instanceof String){
                String strValue = (String) jTablePreferences.getValueAt(i, 0);
                if(!strValue.isEmpty()){
                    if(max < strValue.length() * 7){
                        max = strValue.length() * 7;
                    }
                }
            }
        }
        return max;
    }
        

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jButton2 = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        jButton3 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTablePreferences = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(JDialogPreferencias.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setName("jToolBar1"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(JDialogPreferencias.class, this);
        jButton1.setAction(actionMap.get("aplicarCambios")); // NOI18N
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setName("jButton1"); // NOI18N
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButton1);

        jSeparator1.setName("jSeparator1"); // NOI18N
        jToolBar1.add(jSeparator1);

        jButton2.setAction(actionMap.get("cancelarCambios")); // NOI18N
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setName("jButton2"); // NOI18N
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButton2);

        jSeparator2.setName("jSeparator2"); // NOI18N
        jToolBar1.add(jSeparator2);

        jButton3.setAction(actionMap.get("help")); // NOI18N
        jButton3.setFocusable(false);
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton3.setName("jButton3"); // NOI18N
        jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButton3);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTablePreferences.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTablePreferences.setName("jTablePreferences"); // NOI18N
        jScrollPane1.setViewportView(jTablePreferences);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 342, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JDialogPreferencias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JDialogPreferencias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JDialogPreferencias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JDialogPreferencias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                JDialogPreferencias dialog = new JDialogPreferencias(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    @Action
    public void aplicarCambios() {
        if(Utileria.confirmarOrden(CuatroApp.getApplication().getMainFrame(), "¿Desea Aplicar los Cambios Realizados?", "")){
            for(int j = 0; j < this.jTablePreferences.getRowCount(); j++){
                TypeOptionPreferences objOpcion = (TypeOptionPreferences) this.jTablePreferences.getValueAt(j, 1);
                if(objOpcion != null){
                    switch(objOpcion.getType()){
                        case TypeOptionPreferences.TYPE_BOOLEAN:
                            UtilOpciones.objPreferences.updateOpcion(
                                    objOpcion.getKey(), 
                                    Boolean.parseBoolean(objOpcion.getValue()));
                            break;
                    }
                }
            }
            Bandera objBandera = new Bandera();
            objBandera.addObserver((Observer) objParent);            
            objBandera.setEstado(Bandera.UPDATE_PREFERENCES);                                                      
            objBandera.notificar();  
            dispose();
        }
    }

    @Action
    public void cancelarCambios() {
        if(Utileria.confirmarOrden(CuatroApp.getApplication().getMainFrame(), "¿Desea Cancelar los Cambios Realizados?", "")){
            dispose();
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JTable jTablePreferences;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration//GEN-END:variables

    public void update(Observable o, Object arg) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Action
    public void help() {
        UtilRender.openDialogHelp(JDialogPreferencias.class, getTitle());
    }
}
